const db = require('../config/db')
const bannerModel = '../schema/banner'
const productModel = '../schema/product'
const Mall = db.MallSequelize
const banner_list = Mall.import(bannerModel)
const product = Mall.import(productModel)
product.hasOne(banner_list)
banner_list.belongsTo(product)
// 获取banner列表
const getBanners = async (query) => {
  let page = Number(query.page)
  let limit = Number(query.limit)
  const result = await banner_list.findAndCountAll(
    {
      include: [product],
      offset: parseInt(page*10)*parseInt(limit/10),
      limit: limit,
      order: [['updated_at', 'desc']]
    }
  )
  return result
}
// 添加banner
const addBanner = async (data) => {
  await banner_list.create(
    {
      image_url: data.image_url,
      product_id: data.product_id,
      status: 1,
      is_banner: data.is_banner
    }
  )
  return true
}
// 根据id获取banner
const getBannerById = async (id) => {
  const result = await banner_list.findAll({
    where: {
      id: id
    }
  })
  return result
}
// 更新banner
const updateBanner = async (id, data) => {
  await banner_list.update(
    {
      image_url: data.image_url,
      product_id: data.product_id,
      is_banner: data.is_banner
    },
    {
      where: {
        id: id
      }
    }
  )
  return true
}
module.exports = {
  getBanners,
  getBannerById,
  addBanner,
  updateBanner
}